package com.cos.hospital.ui.main;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;

import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.code.helper.KTextWatcher;
import com.cos.hospital.code.helper.MyOnFreshListener;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.PatientListBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.PatientPinComparator;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.main.adapter.PatientAdapter;
import com.cos.hospital.ui.patient.PatientInfoActivity;
import com.cos.hospital.ui.patient.SearchAcitvity;
import com.cos.hospital.ui.patient.SendMessageActivity;
import com.cos.hospital.widget.MyDividerDecoration;
import com.github.promeg.pinyinhelper.Pinyin;
import com.gjiazhe.wavesidebar.WaveSideBar;
import com.google.gson.JsonObject;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;

/**
 * 患者管理
 */
public class PatientFragment extends MainFragment {
    @BindView(R.id.edt_search)
    EditText edt_search;
    @BindView(R.id.springView)
    SpringView springView;
    @BindView(R.id.rc)
    RecyclerView rc;
    @BindView(R.id.sideBar)
    WaveSideBar sideBar;//侧边索引栏
    private List<PatientListBean.ItemsBean> list;
    private PatientAdapter adapter;
    private PatientPinComparator pinyinComparator;
    private int pageIndex = 1;
    private int searchResultOldPositon = -1;

    @Override
    protected int layout() {
        return R.layout.frag_patient;
    }

    @Override
    protected void init() {
        springView.setHeader(new DefaultHeader(context));
        list = new ArrayList<>();
        adapter = new PatientAdapter(list);
        adapter.openLoadAnimation();
        rc.setLayoutManager(new LinearLayoutManager(context));
        adapter.setEmptyView(R.layout.lay_empty, rc);
        rc.addItemDecoration(new MyDividerDecoration(Color.TRANSPARENT, 1));
        rc.setAdapter(adapter);
        pinyinComparator = new PatientPinComparator();
        sideBar.setIndexItems("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z", "#");
    }

    @Override
    protected void logic() {
        springView.setListener(new MyOnFreshListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                getList();
            }
        });
        adapter.setOnItemClickListener((adapter, view, position) -> toPatientInfo(position));
        adapter.setOnItemChildClickListener((adapter, view, position) -> toSendMessage(position));
        adapter.setOnLoadMoreListener(() -> {
            pageIndex++;
            getList();
        }, rc);
        sideBar.setOnSelectIndexItemListener(index -> {
            //该字母首次出现的位置
            int position = adapter.getPositionForSection(index.charAt(0));
            if (position != -1) {
                ((LinearLayoutManager) rc.getLayoutManager()).scrollToPositionWithOffset(position, 0);
            }
        });
        edt_search.setOnEditorActionListener((textView, actionId, keyEvent) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String content = textView.getText() + "";
                if (content.length() != 0) {
                    doSearch(content);
                } else {
                    USnackbar.showError(context, "请输入关键字");
                }
            }
            return false;
        });
        edt_search.addTextChangedListener(new KTextWatcher() {
            @Override
            public void afterTextChanged(Editable txtEnd) {
                if (txtEnd.length() == 0) {
                    if (searchResultOldPositon == -1) {
                        return;
                    }
                    if (list.size() == 0) {
                        return;
                    }
                    PatientListBean.ItemsBean itemsBean = list.get(searchResultOldPositon);
                    if (itemsBean == null) {
                        return;
                    }
                    changeItem(itemsBean, false);
                    searchResultOldPositon = -1;
                }
            }
        });
        springView.callFreshDelay();
    }

    private void getList() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("keyword", "");
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("pageIndex", pageIndex);
        jsonObject.addProperty("pageSize", 20);
        UHttp.start(getServes().getPatientList(jsonObject), "患者管理列表", new HttpMsgListener<ResultBean<PatientListBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                springView.onFinishFreshAndLoadDelay();
            }

            @Override
            public void onSuccess(ResultBean<PatientListBean> dto) {
                if (dto.isSuccess()) {
                    PatientListBean resultBean = dto.getResult();
                    if (resultBean != null) {
                        int pageIndex = resultBean.getPageIndex();
                        int pageSize = resultBean.getPageSize();
                        int recordCount = resultBean.getRecordCount();
                        if (pageIndex == 1) {
                            searchResultOldPositon = -1;
                            list.clear();
                            adapter.notifyDataSetChanged();
                        }
                        List<PatientListBean.ItemsBean> itemsBeanList = resultBean.getItems();
                        if (itemsBeanList != null && itemsBeanList.size() != 0) {
                            list.addAll(itemsBeanList);
                            filledData(list);
                            Collections.sort(list, pinyinComparator);
                        }
                        int totalPageCount = MyUtil.getInstance().getTotalPageCount(pageSize, recordCount);
                        if (totalPageCount <= pageIndex) {
                            adapter.loadMoreEnd();
                        } else {
                            adapter.loadMoreComplete();
                        }
                        adapter.notifyDataSetChanged();//特殊情况，特殊处理
                    }
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
            }
        });
    }

    /**
     * 为List中元素填充首字母
     */
    private void filledData(List<PatientListBean.ItemsBean> list) {
        for (PatientListBean.ItemsBean patient : list) {
            String pinyin = Pinyin.toPinyin(patient.getFldPatientName().charAt(0));//将第一个字符转换成拼音
            String substring = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (substring.matches("[A-Z]")) {
                patient.setLetter(substring);
            } else {
                patient.setLetter("#");
            }
        }
    }

    private void toPatientInfo(int position) {
        PatientListBean.ItemsBean itemsBean = list.get(position);
        Intent intent = new Intent(context, PatientInfoActivity.class);
        int fldPatientId = itemsBean.getFldPatientId();
        intent.putExtra(Code.SP.ID, fldPatientId);
        startActivity(intent);
    }

    private void toSendMessage(int position) {
        PatientListBean.ItemsBean itemsBean = list.get(position);
        Intent intent = new Intent(context, SendMessageActivity.class);
        int fldPatientId = itemsBean.getFldPatientId();
        intent.putExtra(Code.SP.ID, fldPatientId);
        startActivity(intent);
    }

    private void doSearch(String content) {
        MyUtil.getInstance().closeInputMethod(getActivity());
        for (int position = 0; position < list.size(); position++) {
            PatientListBean.ItemsBean itemsBean = list.get(position);
            String fldPatientName = itemsBean.getFldPatientName();
            String fldMedicalNum = itemsBean.getFldMedicalNum();
            String fldPatientPhone = itemsBean.getFldPatientPhone();
            if (fldPatientName.equals(content) || fldMedicalNum.equals(content) || fldPatientPhone.equals(content)) {
                searchResultOldPositon = position;
                changeItem(itemsBean, true);
                ((LinearLayoutManager) rc.getLayoutManager()).scrollToPositionWithOffset(position, 0);
                return;
            }
        }

        Intent intent = new Intent(context, SearchAcitvity.class);
        intent.putExtra(Code.SP.CONTENT, content);
        startActivity(intent);
    }

    private void changeItem(PatientListBean.ItemsBean itemsBean, boolean searchResult) {
        itemsBean.setSearchResult(searchResult);
        adapter.notifyItemChanged(searchResultOldPositon);
    }

    @OnClick(R.id.iv_scan)
    public void scan() {
        startActivity(new Intent(context, QRCodeActivity.class));
    }

    @Override
    protected void refresh() {
        if (springView != null) {
            springView.callFreshDelay(200);
        }
    }
}
